package com.security.config;

import com.security.filter.MyFilter;
import com.security.handler.MyAuthenticationFailureHandler;
import com.security.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity //启用Web安全功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyAuthenticationProvider myProvider;
    @Autowired
    private MyAuthenticationSuccessHandler mySuccessHandler;
    @Autowired
    private MyAuthenticationFailureHandler myFailHandler;

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(myProvider);
        // 方式一：在内存中存储用户
//        auth.inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("zhp")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("USER");
        // 方式二：数据库存储用户
        // 方式三：LDAP存储用户
    }

    //定义授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin().loginPage("/loginPage")
                .loginProcessingUrl("/successPage").failureUrl("/failPage")
                .successHandler(mySuccessHandler).failureHandler(myFailHandler)  // 会覆盖上一行代码
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/who").access("@rbacServiceImpl.hasPermission(request, authentication)")
                .anyRequest().authenticated() //对所有请求进行认证
                .and()
                .csrf().disable(); //关闭CSRF

        http.addFilterBefore(new MyFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
